//后端
import { Article } from '@/entity/Article';
import { Service, Inject } from 'typedi'
import { Entity } from '@/utils/orm'
import moment from 'moment';
import { JsonResult, msgList, res } from '@/utils/jsonResult';
import { Essayreq ,Essayupdata} from '@/m_req/Essayreq'
import { Token } from '@/m_req/Token'

@Service()
export class EssayDao {

    @Inject()
    orm!: Entity

    @Inject()
    json!: JsonResult<any>;

    //添加文章
    async Essayadd(params: Essayreq, token: Token): Promise<res<null>> {
        await this.orm.source()
            .insert()
            .into(Article)
            .values([
                {
                    article_user: token.user_id,
                    article_title: params.article_title,
                    article_text: params.article_text,
                    article_backimg: params.article_backimg,
                    categories_id: params.categories_id.toString(),
                    tag_id: params.tag_id.toString(),
                    article_time: moment().valueOf()
                },
            ])
            .execute()

        return this.json.success(null, msgList.Essayadd)
    }

    //文章删除
    async Essaydelete(params:Article): Promise<res<null>> {

        // let ret = await this.orm.get(Article).findBy( {article_id: params.id })
        // console.log("ret",ret,ret.length)

        // console.log("pae",params.id,)
        // if(ret.length>0){
        //     return this.json.success(null, msgList.NoFound,404)
        // }else{
            console.log("asdsad",params)
            let fff = await this.orm.get(Article).remove(params)
            return this.json.success(null, msgList.DeleteSuccess)
        //}
        
    }
    //文章修改
    
    async Essayupdata(params:Essayupdata ): Promise<res<null>> {
        params.categories_id=params.categories_id.toString()
        params.tag_id=params.tag_id.toString()
       
       const data =<Article> await this.orm.get(Article).findOne({ where:{ article_id: params.article_id}})

        data.article_title=params.article_title
        data.article_text=params.article_text
        data.article_backimg=params.article_backimg
        data.categories_id=params.categories_id.toString()
        data.tag_id=params.tag_id.toString()
        console.log("params",params)
        console.log("paramsdao",data)

        // let dfdf:Article= new Article()
        // dfdf.article_id=params.article_id,
        // dfdf.article_backimg=params.article_backimg,
        // dfdf.article_text=params.article_text,
        // dfdf.article_time=params.article_time,
        // dfdf.article_user=params.article_user,
        // dfdf.article_view=params.article_view
        // dfdf.article_title=params.article_title
        // dfdf.categories_id=params.categories_id
        // dfdf.tag_id=params.tag_id

        await this.orm.get(Article).save(data)

        return this.json.success(null, msgList.Essayupdata)
    }
}